package com.store.app.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.CommissionRecordAdapter;
import com.store.app.bean.CommissionRecordBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.widget.AutoListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 佣金余额详情
 * Created by Administrator on 2017/8/29.
 */
public class CommissionBalanceActivity extends BaseActivity
        implements IOnHttpListener, View.OnClickListener {

    private static final int REQ_COMMISSION_INFO = 1;
    private static final int REQ_USABLE_CASH_BALANCE = 2;
    private static final int REQ_COMMISSION_MEMBERS_NUMBER = 3;
    private static final int REQ_ALL_COMMISSION_RECORD_REFRESH = 4;
    private static final int REQ_ALL_COMMISSION_RECORD_LOAD_MORE = 5;
    private static final int REQUEST_QUERY_BANK_NO = 6;

    private LinearLayout llToBeAccounted;
    private LinearLayout llWithdrawMoney;
    private LinearLayout llMembersNum;
    private TextView tvTotal;             // 总佣金
    private TextView tvToBeAccounted;     // 待入账
    private TextView tvWithdrawMoney;     // 提现
    private TextView tvMembersNum;        // 会员数
    // title bar.
    private ImageView ivReturn;
    private TextView title;
    private TextView right;
    private AutoListView lv_commission_record;  //佣金收支记录

    private NetRequest mNetRequest;
    private List<CommissionRecordBean> commissionList = new ArrayList<>();
    private CommissionRecordAdapter adapter;

    private int mPageIndex;
    private double totalCommission = 0.00;      // 总佣金 金额
    private double tobeAccounted = 0.00;        // 待入账佣金 金额
    private String withdrawMoney = "0.00";      // 提现
    private int membersNum = 0;                 // 会员数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commission_balance);
        ExitApplication.getInstance().addActivity(this);
        mPageIndex = 1;
        init();
        initView();
        initClicks();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //EventBus.getDefault().unregister(this);
    }

    private void init() {
        //EventBus.getDefault().register(this);
        mNetRequest = new NetRequest(this);
    }

    /*
    public void onEvent(CouponGoCashBean couponGoCashBean) {
        Log.v("zyl","onEvent 更新流水");
        if (couponGoCashBean.type == 2) {
            tv_wallet.setText(MoneyUtil.addComma(Stores.cash_balance + ""));
            pageNum = 1;
            netRequest.requestQueryCashLog(7, pageNum + "");
            netRequest.requestQueryAccount(5);
            netRequest.requestUsableCashBalanceFind(1);
        }
    }
    */

    private void initClicks() {
        // title bar.
        title.setText("佣金");
        ivReturn.setOnClickListener(this);
        right.setBackgroundResource(R.drawable.super_return_help);
        right.setOnClickListener(this);
        llToBeAccounted.setOnClickListener(this);
        llWithdrawMoney.setOnClickListener(this);
        llMembersNum.setOnClickListener(this);
    }

    private void initView() {
        ivReturn = (ImageView) findViewById(R.id.public_ll_return);
        title = (TextView) findViewById(R.id.tvTitle);
        right = (TextView) findViewById(R.id.public_tv_right);

        llToBeAccounted = (LinearLayout) findViewById(R.id.ll_commission_balance_2b_accounted);
        llWithdrawMoney = (LinearLayout) findViewById(R.id.ll_commission_balance_withdraw_money);
        llMembersNum = (LinearLayout) findViewById(R.id.ll_commission_balance_members_num);
        tvTotal = (TextView) findViewById(R.id.tv_commission_balance_total);
        tvToBeAccounted = (TextView) findViewById(R.id.tv_commission_balance_2b_accounted);
        tvWithdrawMoney = (TextView) findViewById(R.id.tv_commission_balance_withdraw_money);
        tvMembersNum = (TextView) findViewById(R.id.tv_commission_balance_members_num);
        // data list.
        lv_commission_record = (AutoListView) findViewById(R.id.lv_commission_record);
    }

    private void initData() {
        getDataFromServer();
        initListView();
    }

    // 设置佣金数据初始化Adapter
    private void initListView() {
        // lv_commission_record.setDivider(null);
        if (commissionList == null) commissionList = new ArrayList<>();

        adapter = new CommissionRecordAdapter(this, commissionList);
        lv_commission_record.setAdapter(adapter);
        lv_commission_record.setOnRefreshListener(new AutoListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPageIndex = 1;
                mNetRequest.requestAllCommissionList(REQ_ALL_COMMISSION_RECORD_REFRESH, mPageIndex);
                lv_commission_record.onRefreshComplete();
            }
        });
        lv_commission_record.setOnLoadListener(new AutoListView.OnLoadListener() {
            @Override
            public void onLoad() {
                mNetRequest.requestAllCommissionList(REQ_ALL_COMMISSION_RECORD_LOAD_MORE, mPageIndex);
                lv_commission_record.onLoadComplete();
            }
        });
        lv_commission_record.onRefresh();
    }

    private void getDataFromServer() {
        mNetRequest.requestCommissionInfo(REQ_COMMISSION_INFO);
        mNetRequest.requestUsableCashBalanceFind(REQ_USABLE_CASH_BALANCE);
        mNetRequest.requestCommissionMembersNumber(REQ_COMMISSION_MEMBERS_NUMBER);
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.public_ll_return:
                finish();
                break;

            case R.id.public_tv_right:
                intent = new Intent(CommissionBalanceActivity.this, CommissionTipsActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_commission_balance_2b_accounted:
                intent = new Intent(CommissionBalanceActivity.this, Commission2bAccountedActivity.class);
                intent.putExtra("2b_accounted", tobeAccounted);
                startActivity(intent);
                break;

            case R.id.ll_commission_balance_withdraw_money:
                // 这里先进行网络请求，得到返回后，再跳转到“提现”页面。STUPID.
                mNetRequest.requestQueryBankNo(REQUEST_QUERY_BANK_NO);
                break;

            case R.id.ll_commission_balance_members_num:
                intent = new Intent(CommissionBalanceActivity.this, CommissionMembersActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
        showToast("请检查本地网络");
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        dismissProgressDialog();
        if (requestId == REQ_ALL_COMMISSION_RECORD_REFRESH) { // 分页查询--下拉刷新
            try {
                JSONObject data = new JSONObject(result);
                JSONArray jsonArray = data.getJSONArray("list");

                Gson gson = new Gson();
                List<CommissionRecordBean> list = new ArrayList<>();
                CommissionRecordBean temp;
                for (int i = 0; i < jsonArray.length(); i++) {
                    temp = gson.fromJson(jsonArray.getJSONObject(i).toString(), CommissionRecordBean.class);
                    list.add(temp);
                }
                lv_commission_record.onRefreshComplete();

                if (data.getJSONObject("page").getInt("page_no") == mPageIndex) {
                    // 设置footer的展示效果 根据没从从服务器获取的数据的条数判断是否加载完毕
                    lv_commission_record.setResultSize(list.size());
                    commissionList.clear();
                    commissionList.addAll(list);
                    adapter.notifyDataSetChanged();
                    mPageIndex += 1;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if (requestId == REQ_ALL_COMMISSION_RECORD_LOAD_MORE) { // 分页查询--上拉加载
            try {
                JSONObject data = new JSONObject(result);
                JSONArray jsonArray = data.getJSONArray("list");

                Gson gson = new Gson();
                List<CommissionRecordBean> list = new ArrayList<>();
                CommissionRecordBean temp;
                for (int i = 0; i < jsonArray.length(); i++) {
                    temp = gson.fromJson(jsonArray.getJSONObject(i).toString(), CommissionRecordBean.class);
                    list.add(temp);
                }
                lv_commission_record.onLoadComplete();
                if (data.getJSONObject("page").getInt("page_no") == mPageIndex) {
                    lv_commission_record.setResultSize(list.size());
                    commissionList.addAll(list);
                    adapter.notifyDataSetChanged();
                    mPageIndex += 1;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if (requestId == REQUEST_QUERY_BANK_NO) { // 查询银行卡号
            try {
                JSONObject data = new JSONObject(result);
                if (!data.toString().equals("{}")) {
                    String bankName = data.optString("publishing_institutions");
                    String bankNo = data.optString("capital_account");

                    Intent intent = new Intent(CommissionBalanceActivity.this, WithDrawalsActivity.class);
                    intent.putExtra("bankname", bankName);
                    intent.putExtra("bankno", bankNo);
                    intent.putExtra("usable_cash_balance", String.valueOf(withdrawMoney));
                    startActivity(intent);
                } else {
                    showBindBankCardDialog();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (requestId == REQ_COMMISSION_INFO) {
            try {
                JSONObject data = new JSONObject(result);
                totalCommission = data.optDouble("totalAmount", 0.00);
                tobeAccounted = data.optDouble("weekAmount", 0.00);

                tvTotal.setText(MoneyUtil.addComma(String.valueOf(totalCommission)));
                tvToBeAccounted.setText(MoneyUtil.addComma(String.valueOf(tobeAccounted)));
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (requestId == REQ_USABLE_CASH_BALANCE) {
            try {
                JSONObject data = new JSONObject(result);
                withdrawMoney = data.optString("usable_cash_balance", "0.00");
                tvWithdrawMoney.setText(MoneyUtil.addComma(withdrawMoney));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if (requestId == REQ_COMMISSION_MEMBERS_NUMBER) {
            try {
                JSONObject data = new JSONObject(result);
                membersNum = data.optInt("memberNumber", 0);
                tvMembersNum.setText(String.valueOf(membersNum));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private AlertDialog mBindBankCardDialog;
    private void showBindBankCardDialog() {
        AlertDialog.Builder bindBankCardBuilder = new AlertDialog.Builder(this);
        mBindBankCardDialog = bindBankCardBuilder.create();
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.balancedialog, null);
        TextView tv_check = (TextView) view.findViewById(R.id.balandia_check);
        tv_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBindBankCardDialog.dismiss();
                Intent intent = new Intent(CommissionBalanceActivity.this, BindBalanceActivity.class);
                startActivity(intent);
            }
        });
        bindBankCardBuilder.setView(view);
        bindBankCardBuilder.show();
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        dismissProgressDialog();
        showToast(msg);
    }

    /**
     * 在其它 Activity 中启动当前 Activity 。
     *
     * @param activity    启动Activity
     * @param cashBalance 零钱总额
     */
    public static void show(Activity activity, double cashBalance) {
        Intent intent = new Intent(activity, CommissionBalanceActivity.class);
        intent.putExtra("cash_balance", cashBalance);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        activity.startActivity(intent);
    }

}
